<?php
session_start();

$level=array('background:#B7FEA5', 'background:#9AFED9',  'background:#C0CEFE', 'background:#D5A8FD', 'background:#FEFE43', 'background:#F56969');

$cat = $_GET['cat'];
$from = $_GET['from'];
$len=$_GET['len'];

$cat_db=$_SESSION['user']['cat'];
$authorized_cats=explode(',', $cat_db); 

$cur_cat='';

if(strstr($cat, '>')){
        $str=preg_replace('/\s/', '', $cat);
        $parts=explode('>', $cat);
        $str=preg_replace('/\s/', '', $parts[0]);
        $cur_cat=$str;
}

if(! in_array($cur_cat, $authorized_cats)){
        echo "You are not authorized. Pls contact WangWang: wssansbb.!";
        return(0);
}


$rank="";

if($_GET['rank']) {
	$rank=$_GET['rank'];
}else {
	$rank="1";
}

if($_GET['len']) {
	$len=$_GET['len'];
}else {
	$len="20";
}

if($_GET['from']) {
	$from=$_GET['from'];
}else {
	$from="0";
}

if($len<=0 || $len > 300){
	$len=20;
}

$from=($from<0 || $from>5000)?0:$from;
$rank=($rank<=0 || $rank>6)?1:$rank;

$link=mysql_connect('localhost','root','yiqifacai');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$program_char="utf8";
mysql_set_charset($program_char, $link); 
$charset = mysql_client_encoding ($link);
mysql_select_db('keywords');

// 获得最新的日期
$sql="SELECT DISTINCT(date) FROM huazhuangpin ORDER BY date DESC";

$query = mysql_query($sql);
if (!$query) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $sql;
    die($message);
}
$row = mysql_fetch_assoc($query);
$latest_date=$row["date"];

// 获得当前rank下的总词数；
function get_word_count($rank, $cat, $latest_date) {
	// 获取当前优先级别下的词的总个数 
	$sql="SELECT COUNT(*) FROM huazhuangpin where (cat" . $rank . " = \"$cat\" AND date=\"$latest_date\")";

	$query = mysql_query($sql);
	if (!$query) {
	    $message  = 'Invalid query: ' . mysql_error() . "\n";
	    $message .= 'Whole query: ' . $sql;
	    die($message);
	}

	$row = mysql_fetch_array($query);
	$word_count=$row[0];

	return $word_count;
} //get_word_count ends;

$word_count=get_word_count($rank, $cat, $latest_date);

$cat_stats=array();
$cat_stats[1]=get_word_count(1, $cat, $latest_date);

if($cat_stats[1] < 400) {
	$cat_stats[2]=get_word_count(2, $cat, $latest_date);
	$cat_stats[3]=get_word_count(3, $cat, $latest_date);
	$cat_stats[4]=get_word_count(4, $cat, $latest_date);
	$cat_stats[5]=get_word_count(5, $cat, $latest_date);
}

// 做累加的边界使用
$cat_boundary=array();
$cat_boundary[1]=$cat_stats[1];
$cat_boundary[2]=$cat_stats[2] + $cat_boundary[1];
$cat_boundary[3]=$cat_stats[3] + $cat_boundary[2];
$cat_boundary[4]=$cat_stats[4] + $cat_boundary[3];
$cat_boundary[5]=$cat_stats[5] + $cat_boundary[4];


?>
<html>

<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.zclip.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    $("button#CopyTable").zclip({
        path:'js/ZeroClipboard.swf',
        copy:function(){
		var len=$('td#key_words').length;
		var ret="";
		if(len > 0){ 
			$('td#key_words').each(function(i){
				ret=ret+$(this).text()+"\n";
			})
		}
		return ret;
	},
        beforeCopy:function(){
        },
        afterCopy:function(){
            $('td#key_words').css('background','#B7FEA5');
	    alert("亲，关键词已经复制到粘贴板！请粘贴到系统中...");
        }
    });

});

</script>
<title>直通车舵手关键词</title>
</head>
<body>
<p align="center" ><button id="CopyTable" type="button">复制本页关键词到剪贴板</button></p>
<p><form action="keywords.php" method="get">
  开始值:<input type="text" size=5  name="from" />
  关键词个数<input type="text" size=5 name="len" />
  相关性:<input type="text" size=1 name="rank" />
  <input type="hidden" name="cat" value="<?php echo $cat; ?>"/>
 <input type="submit" value="提交" />
</form></p>
<p>
<?php
$stat_str = "当前优先级为: " . $rank;
$stat_str .= ", 共有关键词：" . $word_count;
if($cat_stats[1] < 400) {
	$stat_str .= "<br> 1:$cat_stats[1], 2:$cat_stats[2], 3:$cat_stats[3], 4:$cat_stats[4], 5:$cat_stats[5]";
}
echo $stat_str;

?>
</p>

<table id='KeyWords' border="1">
  <tr>
    <th>序号</th>
    <th>更新日期</th>
    <th>关键词</th>
    <th>搜索次数</th>
    <th>平均出价</th>
    <th title="从好到坏匹配，深绿，浅绿，浅青，浅蓝，浅紫色，淡黄色，暗红色，分别对应匹配级别，1，2，3，4 ...">优先类目</th>
  </tr>

<?php
$num=1;
global $word_count, $rank, $cat, $latest_date, $len, $cat_stats, $cat_boundary;

function print_data($rank, $cat, $latest_date, $from, $len) { 
	global $level, $num, $cat_boundary,$rank;
	$color=$level[$rank-1];
	if($from < $cat_boundary[1] && $from > 0){
		$rank=1;
	}elseif($from >= $cat_boundary[1] && $from < $cat_boundary[2]){
		$rank=2;
		$from=$from-$cat_boundary[1];
	}elseif($from >= $cat_boundary[2] && $from < $cat_boundary[3]){
                $rank=3;
                $from=$from-$cat_boundary[2];
	}elseif($from >= $cat_boundary[3] && $from < $cat_boundary[4]){
                $rank=4;
                $from=$from-$cat_boundary[3];
	}elseif($from >= $cat_boundary[5] ){
		$ret_str = "<tr><td align=\"center\" colspan=6>无结果</td></tr>";
		echo $ret_str;
		return 0; // 已经越界了，直接显示无结果
	}
	$sql = "SELECT date,word, times, price,cat1 FROM  huazhuangpin where (cat" . $rank . " = \"$cat\" AND date=\"$latest_date\")  ORDER BY times DESC LIMIT $from, $len";
	$query = mysql_query($sql);
	if (!$query) {
	    $message  = 'Invalid query: ' . mysql_error() . "\n";
	    $message .= 'Whole query: ' . $sql;
	    die($message);
	}
	
	$ret_str="";
	while($row = mysql_fetch_assoc($query)){
		$ret_str = "<tr><td>";
		$ret_str .= $num++ . "</td><td>";
		$ret_str .= $row["date"] . "</td><td id='key_words'>";
		$ret_str .= $row["word"] . "</td><td>";
		$ret_str .= $row["times"] . "</td><td>";
		$ret_str .= $row["price"] . "</td><td title=\"类目优先级别为: $rank\" style=\"" . $color . "\">";
		$ret_str .= $row["cat1"] . "</td></tr>";
		echo $ret_str;
	} // while ends here.
} // Print data ends here.

print_data($rank, $cat, $latest_date, $from, $len);
if($from < $cat_boundary[5]){
	while($num <= 200 && $rank < 6 && $len==200){
		$tmp_count=get_word_count(++$rank, $cat, $latest_date);
		print_data($rank, $cat, $latest_date, 0, 200-$num);
	}
}
?>
</table>
</body>

</html>
